<?php
namespace Admin\Frontend\Controllers;

use Admin\Models\school\XHSchoolVisit;
use Admin\Models\school\XHSchoolVisitRecord;
use Admin\Models\school\XHSchoolVisitType;
use Helpers\Main;
use Helpers\Assets;
use Helpers\Template;
use Helpers\Tool;
use Helpers\User;
use Helpers\UserPower;
use Helpers\XhException;
use Modules\Customer;
use Modules\School;
use Phalcon\Di;

class SchoolVisitController extends ControllerBase
{
    public static $status = [1 => '待审批' , 2 => '审批通过' , 3 =>'审批不通过'];
    private static $enmu = [
        'iStatus' => [
            1 => '待审批',
            2 => '审批通过',
            3 => '审批不通过',
        ],
    ];

    /**
     * 外校参观
     *
     * @return \Phalcon\Mvc\View
     *
     * create by fyh 20181114
     */
    public function schoolVisitAction()
    {
        Assets::easyUI();
        Assets::importJs('js/school_visit/schoolVisit.js');
        $this->view->pick('school_visit/schoolVisit');
        Template::exists('XHSchool_Visit', 'list') or die(
            Main::showMessageModal('XHSchool_Visit.xml 配置文件不存在，请先创建！', 109106002)
        );
        $listButtonArr =$listSearchArr= [];
        if (UserPower::checkUserPower('School_Visit_Add')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_add', 'text' => '新增', 'icon' => 'fa-plus');
        }
        if (UserPower::checkUserPower('School_Visit_Del')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash');
        }
        $listSearchArr[] = array('type'=>'select', 'id'=>'list_search_timeType','style'=>'width:120px', 'data' => [
            'a.iStarttime' => '活动开始时间',
            'a.iEndtime' => '活动结束时间',
            'a.tCreateDate' => '创建时间',
            'a.tLastModifyDate' => '修改时间'
        ],'default'=>'a.tStartTime');

        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search_startTime', 'label' => ' ',
            'class'=>'easyui-datebox','style'=>'width:100px !important ;');
        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search_endTime', 'label' => ' ~',
            'class'=>'easyui-datebox','style'=>'width:100px !important ;');
        $listSearchArr[] = array(
            'type' => 'button',
            'id' => 'bt_list_search',
            'text' => '查找',
            'icon' => 'fa-search',
            'style' => 'margin-left:10px'
        );
        return $this->view->setVars(array(
            'List'       => Template::createList('list', 'XHSchool_Visit', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
        ));
    }

    /**
     * 获取外校参观数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by fyh 20181114
     */
    public function getSchoolVisitAction()
    {
        try {
            $schoolId = $this->request->getPost('schoolId', 'int');
            $status     = $this->request->getPost('status', 'int');
            $timeType = $this->request->getPost('timeType', 'string');
            $startTime = $this->request->getPost('startTime', 'string');
            $endTime   = $this->request->getPost('endTime', 'string');
            $builder  = $this->modelsManager->createBuilder()
                ->columns('*')
                ->from(['a'=>'Admin\Models\school\XHSchoolVisit'])
                ->where('a.bDelete=0')->orderBy('a.tLastModifyDate desc');
            if ($schoolId) {
                $builder->andWhere('a.iSchoolId = :iSchoolId:', ['iSchoolId' => $schoolId]);
            }
            if ($timeType) {
                if ($startTime && $endTime) {
                    if ($timeType == 'a.iStarttime' || $timeType == 'a.iEndtime') {
                        $builder->andWhere(
                            " from_unixtime(".$timeType.",'%Y-%m-%d') >= :startTime: and
                            from_unixtime(".$timeType.",'%Y-%m-%d') <= :endTime:",
                            ['startTime' => $startTime, 'endTime' => $endTime]
                        );
                    } else {
                        $builder->andWhere(
                            " DATE_FORMAT(".$timeType.",'%Y-%m-%d') >= :startTime: and
                            DATE_FORMAT(".$timeType.",'%Y-%m-%d') <= :endTime:",
                            ['startTime' => $startTime, 'endTime' => $endTime]
                        );
                    }
                } elseif ($startTime) {
                    if ($timeType == 'a.iStarttime' || $timeType == 'a.iEndtime') {
                        $builder->andWhere(
                            " from_unixtime(" . $timeType . ",'%Y-%m-%d') >= :startTime:",
                            ['startTime' => $startTime]
                        );
                    } else {
                        $builder->andWhere(
                            " DATE_FORMAT(" . $timeType . ",'%Y-%m-%d') >= :startTime:",
                            ['startTime' => $startTime]
                        );
                    }
                } elseif ($endTime) {
                    if ($timeType == 'a.iStarttime' || $timeType == 'a.iEndtime') {
                        $builder->andWhere(
                            " from_unixtime(" . $timeType . ",'%Y-%m-%d') <= :endTime:",
                            ['endTime' => $endTime]
                        );
                    } else {
                        $builder->andWhere(
                            " DATE_FORMAT(" . $timeType . ",'%Y-%m-%d') <= :endTime:",
                            ['endTime' => $endTime]
                        );
                    }
                }
            }
            $staff = false;
            $schoolIds =  School::getMergePower($staff ? $staff['userId'] : null, false);
            if ($schoolIds !== true) {
                if (count($schoolIds) > 0) {
                    $builder->andWhere('a.iSchoolId in ({schoolIds:array})', ['schoolIds' => $schoolIds]);
                } else {
                    return $this->sendJsonResponse(['total' => 0, 'rows' => []]);
                }
            }
            if ($status) {
                $builder->andWhere('a.iStatus = :status:', ['status' => $status]);
            }
            $data = Main::runBuilderPage($builder, ['iStatus' => self::$status]);
            Main::runUserNameById(
                $data['rows'],
                ['iCreateUserId' => 'iCreateUserId', 'iLastModifyUserId' => 'iLastModifyUserId'],
                true
            );
            Tool::runTimestamp($data['rows'], 'iStarttime');
            Tool::runTimestamp($data['rows'], 'iEndtime');
            Tool::runEnum($data['rows'], self::$enmu);
            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 活动表单
     *
     *  @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|\Phalcon\Mvc\View|string
     *
     * create by fyh 20181115
     */
    public function actFormAction()
    {
        $iId = $this->request->getQuery('iId', 'int');
        $schoolId = $this->request->getQuery('schoolId', 'int');
        if (!$schoolId) {
            return $this->sendViewError('缺少参数');
        }
        $result['schoolId'] = $schoolId;
        Assets::easyUI();
        Assets::select2();
        Assets::datetimePicker();
        Assets::viewer();
        $this->di->get('assets')
            ->addCss('assets/fileinput/fileinput.css')
            ->addJs('customer/js/fileinput.min.js')//修改过的
            ->addJs('customer/js/zh.js');
        Assets::easyUI('../customer/js/myMain.js');
        Assets::importJs('js/school_visit/actForm.js');
        $this->view->pick('school_visit/actForm');
        try {
            if (!empty($iId)) {
                $result['iId'] = $iId;
                $schoolvisit=XHSchoolVisit::findFirst([
                    'conditions'=>'bDelete=0 AND iId=:iId:',
                    'bind'=>['iId'=>$iId],
                ])->toArray();
                $schoolvisit['iStarttime'] = date('Y-m-d H:i:s', $schoolvisit['iStarttime']);
                $schoolvisit['iEndtime'] = date('Y-m-d H:i:s', $schoolvisit['iEndtime']);
                $visitType=XHSchoolVisitType::find([
                    'conditions'=>'bDelete=0 AND iSVId=:iSVId:',
                    'bind'=>['iSVId'=>$iId],
                ])->toArray();
                $visitRecord=XHSchoolVisitRecord::find([
                    'conditions'=>'bDelete=0 AND iSVId=:iSVId:',
                    'bind'=>['iSVId'=>$iId],
                ])->toArray();
                $this->view->setVars([
                    'info' => isset($schoolvisit)? json_encode($schoolvisit):'',
                    'visitType' => isset($visitType)? json_encode($visitType):'',
                    'visitRecord' => isset($visitRecord)? json_encode($visitRecord):'',
                ]);
            }
            $arr['customer'] = Customer::getCustomerNames();
            return $this->view->setVars([
                'targets' => $arr,
                'schoolId' => $schoolId,
                'iId' => $iId,
                'enmuType' => XHSchoolVisitType::$visitType,
            ]);
        } catch (\Exception $e) {
            return $this->sendViewError($e->getMessage());
        }
    }

    /**
     * ajax上传附件
     *
     * create by fyh 20181115
     */
    public function ajaxUploadAction()
    {
        $this->view->disable();
        if (!$this->request->hasFiles()) {
            return $this->sendErrorResponse(400, '没有上传文件');
        };
        $file = $this->request->getUploadedFiles()[0];
        try {
            $fileName = $file->getName();
            $fullPath = TEMP_PATH . $fileName;
            if (!is_writable(TEMP_PATH)) {
                return $this->sendJsonResponse(['state' =>  TEMP_PATH . '缓存无写入权限']);
            }
            $file->moveTo($fullPath);
            $url = Main::uploadToFileManageSystem($fullPath, 'other', null, true);
            @unlink($fullPath);
            return $this->sendJsonResponse(['url' => $url, 'fileName' => $fileName]);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * ajaxDelete删除附件
     * @param null $fileType
     * @return bool|\Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by fyh 20181115
     */
    public function ajaxDeleteAction($fileType = null)
    {
        $this->view->disable();
        $iId = $this->request->getPost('iId', 'int');
        if (!$iId) {
            return $this->sendErrorResponse('400', '缺少参数');
        }
        $rmId = $this->request->getPost('rmId', 'int');
        if ($rmId == null) {
            return $this->sendErrorResponse('400', '缺少参数');
        }
        $obj = XHSchoolVisit::findFirst($iId);
        $image = $obj->toArray();
        if ($fileType == 'fileDelete') {//删除日程
            $images = explode(',', $image['mESchedule']);
            $url = '';
            foreach ($images as $key => $value) {
                if ($key != $rmId && $value != '') {
                    $url = $url . $value . ',';
                }
            }
            $obj->mESchedule = $url;
        } else {
            $images = explode(',', $image['mEPhotos']);
            $url = '';
            foreach ($images as $key => $value) {
                if ($key != $rmId && $value != '') {
                    $url = $url . $value . ',';
                }
            }
            $obj->mEPhotos = $url;
        }
        try {
            $obj->save();
            return $this->sendSuccessResponse('成功');
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * 保存  添加、编辑
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * created by fyh 20181115
     */
    public function saveSchoolVisitAction()
    {
        if (!UserPower::checkUserPower('School_Visit_Add')) {
            return $this->sendErrorResponse(500, '没有权限');
        }
        if (!UserPower::checkUserPower('School_Visit_Edit')) {
            return $this->sendErrorResponse(403, '没有权限');
        }
        $data = $this->request->getPost();
        if (empty($data['iId'])) {
            unset($data['iId']);
        }
        unset($data['mEPhotos']);
        unset($data['mESchedule']);
        try {
            $transaction = Di::getDefault()->get('db');
            $transaction->begin();
            //处理外校参观主表
            $data['iStarttime'] = strtotime($this->request->getPost('iStarttime'));
            $data['iEndtime'] = strtotime($this->request->getPost('iEndtime'));
            if ($this->request->getPost('mEPhotos')) {
                $data['mEPhotos'] .= $this->request->getPost('mEPhotos');
            }
            if ($this->request->getPost('mESchedule')) {
                $data['mESchedule'] .= $this->request->getPost('mESchedule');
            }
            $data['iStatus'] = 2;
            if ($data['iId']) {
                $obj = XHSchoolVisit::findFirst('iId='.$data['iId']);
                $data['mEPhotos'] .= $obj->mEPhotos;
                $data['mESchedule'] .= $obj->mESchedule;
                $obj->update($data);
                $iId = $data['iId'];
            } else {
                $obj = new XHSchoolVisit();
                if (!$iId = $obj->save($data)) {
//                    $transaction->rollback();
                    throw new XhException($iId);
                }
            }
            //处理参观流程
            if ($sName = $this->request->getPost('sName')) {
                $sName_count = count($sName);
                for ($i = 0; $i < $sName_count; $i++) {
                    if (!empty($data['sName'][$i])) {
                        $typeData = [
                            'iSVId' => $iId,
                            'sName' => $data['sName'][$i],
                            'sContent' => $data['sContent'][$i],
                        ];
                        if ($TypeId=$this->request->getPost('iTId')) {
                            if ($TypeId[$i]) {
                                $objType = XHSchoolVisitType::findFirst("iTId =".$TypeId[$i]);
                                $objType->update($typeData);
                            } else {
                                $objType = new XHSchoolVisitType();
                                if (!$objType->save($typeData)) {
                                    $transaction->rollback();
                                    throw new XhException('操作失败');
                                }
                            }
                        } else {
                            $objType = new XHSchoolVisitType();
                            if (!$objType->save($typeData)) {
                                $transaction->rollback();
                                throw new XhException('操作失败');
                            }
                        }
                    }

                }
            }
            //处理参观学校记录
            if ($iCustomerId = $this->request->getPost('iCustomerId')) {
                $iCustomerId_count = count($iCustomerId);
                $iPeopleNum = 0;
                for ($i = 0; $i < $iCustomerId_count; $i++) {
                    if (!empty($data['iCustomerId'][$i])) {
                        $recordData = [
                            'iSVId' => $iId,
                            'iCustomerId' => $data['iCustomerId'][$i],
                            'iPeopleNum' => $data['iPeopleNum'][$i],
                        ];
                        $iPeopleNum += $data['iPeopleNum'][$i];
                        if ($RecordId=$this->request->getPost('iRId')) {
                            if ($RecordId[$i]) {
                                $objRecord = XHSchoolVisitRecord::findFirst("iRId =".$RecordId[$i]);
                                $objRecord->update($recordData);
                            } else {
                                $objRecord = new XHSchoolVisitRecord();
                                if (!$objRecord->save($recordData)) {
                                    $transaction->rollback();
                                    throw new XhException('操作失败');
                                }
                            }
                        } else {
                            $objRecord = new XHSchoolVisitRecord();
                            if (!$objRecord->save($recordData)) {
                                $transaction->rollback();
                                throw new XhException('操作失败');
                            }
                        }
                    }
                }
                $data['iSchoolCount'] = $iCustomerId_count;
                $data['iPeopleCount'] = $iPeopleNum;
                $obj = XHSchoolVisit::findFirst('iId='.$iId);
                $obj->update($data);
            }
            $transaction->commit();
            return $this->sendSuccessResponse('保存成功');
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $data);
        }
    }
    /**
     * 删除活动
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by fyh 20181122
     */
    public function delSchoolVisitAction()
    {
        try {
            $iId = $this->request->getPost('iId', 'int');
            if (!$iId) {
                return $this->sendErrorResponse('400', '缺少参数');
            }
            $obj = XHSchoolVisit::findFirst($iId);
            if (!User::isAdmin() && $obj->iCreateUserId != Main::getLoginUserInfo('userId')) {
                return $this->sendErrorResponse(401, '没有权限');
            }
            if (!UserPower::checkUserPower('School_Visit_Edit')) {
                return $this->sendErrorResponse(403, '没有权限');
            }
            $obj->bDelete = 1;
            if (!$obj->save()) {
                return $this->sendErrorResponse(500, '保存失败');
            }
            return $this->sendSuccessResponse('保存成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }
}